package org.butterfly.watchdog.config;

import org.butterfly.watchdog.WatchDog;
import org.butterfly.watchdog.WatchDogField;
import org.butterfly.watchdog.annotations.EnableWatchDog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportAware;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

import java.util.Map;

/**
 * set WatchDog configuration
 *
 * @author drake
 * @since 2022/3/29
 */
@Configuration
public class WatchDogConfiguration implements ImportAware {

    @Autowired
    WatchDog watchDog;

    @Override
    public void setImportMetadata(AnnotationMetadata importMetadata) {
        Map<String, Object> attrsMap = importMetadata.getAnnotationAttributes(EnableWatchDog.class.getName());
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(attrsMap);
        if (attributes == null) {
            return;
        }
        watchDog.setEnable(attributes.getBoolean(WatchDogField.ENABLE));
        watchDog.setFirstDelay(attributes.getNumber(WatchDogField.FIRST_DELAY));
        watchDog.setPeriod(attributes.getNumber(WatchDogField.PERIOD));
    }
}
